/**
 * @Description: api 多节点控制，支持同一个请求，短时间重复的过滤
 */
import axios from "axios";
import qs from "qs";
import md5 from "md5";
import { Message } from "iview";
import Cookies from "js-cookie";
import { TOKEN_KEY } from "@/libs/util";

//发送请求的管理，同一请求在没有返回的情况下或者超时返回，不能反复请求
let requestManagement = {};

//API全局配置,不同站点，传递参数，配置都不一样，迁移到具体站的内部配置
/*
axios.defaults.baseURL = config.baseURL;
axios.defaults.timeout = 60000;
axios.defaults.withCredentials = true;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.transformRequest = [
  function(data, headers) {
    //return a string or an axios of Buffer, ArrayBuffer,FormData or Stream
    //return JSON.stringify(data);
    return qs.stringify(data);
    //return data;
  }
];
*/

//请求拦截器
axios.interceptors.request.use(
  function(config) {
    //console.log("request", config);
    config = requestUrl(config);
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

//返回拦截器
axios.interceptors.response.use(
  function(response) {
    //console.log("response", response);
    responseUrl(response.config);
    return response;
  },
  function(error) {
    return Promise.reject(error);
  }
);

/*
 * 拦截相同带参数的API，在第一个API没有回来前，后面都会被忽略
 */
function requestUrl(config) {
  let strData = "";
  if (config.data) {
    strData = JSON.stringify(config.data);
  }
  let requestId = md5(config.url + strData);
  if (requestManagement[requestId] && requestManagement[requestId].count > 2) {
    return Promise.reject({
      type: 1,
      msg: "请求被取消,监测该请求到短时间频繁重复请求异常情况！"
    });
  } else {
    let count = requestManagement[requestId]
      ? requestManagement[requestId].count + 1
      : 1;
    requestManagement[requestId] = { createTime: new Date(), count: count };
  }
  config.requestId = requestId;
  return config;
}

//响应后，删除请求
function responseUrl(config) {
  if (requestManagement[config.requestId]) {
    delete requestManagement[config.requestId];
  }
}

//axios请求封装
export const request = function(data) {
  return new Promise((resolve, reject) => {
    //console.log(data);
    axios(data)
      .then(function(response) {
        let { data } = response;
        if (data.code !== 200) {
          if (data.code === 401) {
            Cookies.remove(TOKEN_KEY);
            Message.error("没有权限,请登录后使用！");
            setTimeout(function() {
              window.location.href = "/";
            }, 2000);
            reject(data);
          } else {
            /*
            if (data.msg) {
              Message.error({
                duration: 2,
                content: data.msg
              });
            } else {
              Message.error("服务内部错误");
            }
            */
            reject(data);
          }
        } else {
          resolve(data);
        }
      })
      .catch(function(error) {
        //Message.error("服务内部错误");
        console.log("Request error:", data.url, error);
        if (error.type == 1) {
          Message.error({
            duration: 4,
            content: error.msg
          });
        } else {
          reject(error);
        }
      });
  });
};

//多个请求封装 data:[API.getA(obj),API.getB(obj)]
export const requestAll = function(data) {
  Promise.all(data)
    .then(result => {
      resolve(result);
    })
    .catch(error => {
      reject(error);
    });
};

/****************************** 基础平台 医院类 通用api **************************/
//API login
export const login = obj => {
  let requestData = {
    method: "post",
    url: "login",
    data: obj
  };
  return request(requestData);
};

//API logout
export const logout = obj => {
  let requestData = {
    method: "get",
    url: "logout"
  };
  return request(requestData);
};

//API editPW
export const editPW = obj => {
  let requestData = {
    method: "POST",
    //url: "Modify/CModifyPass",
    url: "eidtpw",
    params: obj
  };
  return request(requestData);
};
